// 导包
const express = require('express');
const router = express.Router();
const Email = require('../../common/emailApi');

// 发送邮件
router.get('/send', async function (req, res) {
    //接收邮箱
    let email = req.query.email;
    // console.log(email)
    //邮箱正则表达式
    let rep = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
    //判断格式是否正确
    if (rep.test(email)) {
        //调用发送邮件的方法
        Email.getEmailCode(email)
            .then(
                () => {
                    res.send({
                        code: 200,
                        msg: "验证码发送成功。"
                    })
                }
            )
            .catch(
                err => {
                    res.send({
                        code: 200,
                        msg: "验证码发送失败。",
                        err 
                    })
                }
            )
    } else {
        res.send({
            code: -1,
            msg: "邮箱格式不正确。"
        })
    }
})

// 测试邮箱验证
router.get('/verify', async function (req, res) {
    //接收邮箱
    let email = req.query.email;
    let code = req.query.code;
    // 检查代码是否执行到此处
    // console.log({email,code});
    await Email.verifyEmailCode(email,code)
    .then(
        content=>{
            res.send(content)
        }
    )
    .catch(
        err=> {
            res.send(err)
        }
    )
})

module.exports = router;